package small.common.core.util;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

public class MethodUtil {

    private static final Map<Method, String> methodNameMap = new ConcurrentHashMap<Method, String>();

    private static final Object LOCK = new Object();

    /**
     * 分析并解析方法名，然后缓存到映射
     *
     * @param method 方法实例
     * @return 解析的方法名
     */
    public static String resolveMethodName(Method method) {
        if (method == null) {
            throw new IllegalArgumentException("Null method");
        }
        String methodName = methodNameMap.get(method);
        if (methodName == null) {
            synchronized (LOCK) {
                methodName = methodNameMap.get(method);
                if (methodName == null) {
                    StringBuilder sb = new StringBuilder();

                    String className = method.getDeclaringClass().getName();
                    String name = method.getName();
                    Class<?>[] params = method.getParameterTypes();
                    sb.append(className).append(":").append(name);
                    sb.append("(");

                    int paramPos = 0;
                    for (Class<?> clazz : params) {
                        sb.append(clazz.getCanonicalName());
                        if (++paramPos < params.length) {
                            sb.append(",");
                        }
                    }
                    sb.append(")");
                    methodName = sb.toString();

                    methodNameMap.put(method, methodName);
                }
            }
        }
        return methodName;
    }


    /**
     * 判断所有方法上是否有指定注解
     * @return
     */
    public static boolean hasAdaptiveMethod(Method[] methods,Class<? extends Annotation> annotationClass) {
        return Arrays.stream(methods).anyMatch(m -> m.isAnnotationPresent(annotationClass));
    }

    /**
     * 判断是否
     * @param method
     * @param args
     * @return
     */
    public static boolean isObjectMethod(Method method, Object[] args){
        if (method.getDeclaringClass() == Object.class) {
            return true;
        }
        String methodName = method.getName();
        Class<?>[] parameterTypes = method.getParameterTypes();
        if (parameterTypes.length == 0) {
            if ("toString".equals(methodName)) {
                return true;
            } else if ("$destroy".equals(methodName)) {
                return true;
            } else if ("hashCode".equals(methodName)) {
                return true;
            }
        } else if (parameterTypes.length == 1 && "equals".equals(methodName)) {
            return true;
        }
        return false;
    }

    /**
     * For test.
     */
    static void clearMethodMap() {
        methodNameMap.clear();
    }
}
